<template>
  <div class="boxTitle2">数据日志</div>
  <div class="data_day" id="demo" style="width:100%;overflow:hidden;height: 80%;">
    <div class="scroll-container">
      <table style="text-align: left;margin-left:10%;width:80%;">
        <tbody id="demo1" class="scroll-content">
          <tr v-for="(item, index) in dataList" :key="index">
            <td>{{ index + 1 }}</td>
            <td>{{ item.sensorName }}</td>
            <td>{{ item.time }}</td>
          </tr>
        </tbody>
        <tbody id="demo2" class="scroll-content"></tbody>
      </table>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, onUnmounted } from 'vue'
import { getAccessToken } from "@/utils/auth"
import '../css/reset.css'
import '../css/new_index.css'

// 传感器名称映射
const sensorNames: any = {
  1: '水质PH传感器',
  2: '水质EC传感器',
  3: '水质溶解氧传感器',
  4: '无线土壤温湿度传感器',
  5: '无线土壤温湿度传感器',
  6: '无线土壤温湿度传感器',
  7: '太阳能移动无线土壤温湿度传感器',
  8: '无线土壤氮磷钾传感器',
  9: '无线土壤氮磷钾传感器',
  10: '无线土壤氮磷钾传感器',
  11: '太阳能移动无线土壤氮磷钾传感器',
  12: '无线土壤酸碱度传感器',
  13: '无线土壤酸碱度传感器',
  14: '无线土壤酸碱度传感器',
  15: '太阳能移动无线土壤酸碱度传感器',
  16: '空气温湿度传感器',
  17: '光照传感器',
  18: '光照传感器',
  19: '二氧化碳传感器'
}

// 数据列表
const dataList = ref<any[]>([])

// 滚动相关变量
let scrollTimer: any = null
const scrollSpeed = 30 // 滚动速度，数值越大滚动越快

// 获取设备列表
const getDeviceList = async () => {
  try {
    let token = getAccessToken()

    if (!token) {
      const wsCache = new (window as any).WebStorageCache({
        storage: 'localStorage'
      })
      token = wsCache.get('ACCESS_TOKEN')
    }

    const baseUrl = import.meta.env.VITE_BASE_URL || ''
    let url = `${baseUrl}/admin-api/eiot/device/page?pageNo=1&pageSize=100`

    const requestOptions: any = {
      method: 'GET',
      headers: {}
    }

    if (token) {
      requestOptions.headers['Authorization'] = `Bearer ${token}`
    }

    const response = await fetch(url, requestOptions)

    if (!response.ok) {
      throw new Error(`HTTP error! status: ${response.status}`)
    }

    const text = await response.text()

    if (text.includes('<!DOCTYPE html') || text.includes('<html') || text.includes('login')) {
      return []
    }

    try {
      const result = JSON.parse(text)
      if (result && result.code === 0 && result.data && Array.isArray(result.data.list)) {
        return result.data.list
      } else if (result && Array.isArray(result.list)) {
        return result.list
      } else {
        return []
      }
    } catch (jsonError) {
      throw new Error('API返回的数据不是有效的JSON格式')
    }
  } catch (error) {
    return []
  }
}

// 获取数据日志
const getDataLogs = async () => {
  try {
    let token = getAccessToken()

    if (!token) {
      const wsCache = new (window as any).WebStorageCache({
        storage: 'localStorage'
      })
      token = wsCache.get('ACCESS_TOKEN')
    }

    const baseUrl = import.meta.env.VITE_BASE_URL || ''
    const url = `${baseUrl}/admin-api/eiot/device/deviceLogs/list`

    // 获取设备列表以获取第一个设备的ID
    const devices = await getDeviceList()
    if (!Array.isArray(devices) || devices.length === 0) {
      throw new Error('未找到设备')
    }
    const deviceId = devices[0].id

    const requestOptions: any = {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json'
      },
      body: JSON.stringify({
        deviceId: deviceId,
        pageNo: 1,
        pageSize: 100
      })
    }

    if (token) {
      requestOptions.headers['Authorization'] = `Bearer ${token}`
    }

    const response = await fetch(url, requestOptions)

    if (!response.ok) {
      throw new Error(`HTTP error! status: ${response.status}`)
    }

    const text = await response.text()

    if (text.includes('<!DOCTYPE html') || text.includes('<html') || text.includes('login')) {
      return []
    }

    try {
      const result = JSON.parse(text)
      // 检查返回的数据结构
      if (result && result.code === 0 && result.data && Array.isArray(result.data.list)) {
        // 过滤出identifier为"report"的数据
        const reportData = result.data.list.filter((item: any) => item.identifier === "report")
        
        // 处理数据格式
        const formattedData = reportData.map((item: any) => {
          // 获取传感器编号
          const sensorNumber = item.data?.sensor
          // 获取传感器名称
          const sensorName = sensorNumber ? sensorNames[sensorNumber] || `传感器${sensorNumber}` : '未知传感器'
          
          return {
            id: item.id || '',
            sensorName: sensorName,
            time: item.time ? new Date(item.time).toLocaleString() : ''
          }
        })
        
        return formattedData
      } else {
        return []
      }
    } catch (jsonError) {
      console.error('解析JSON失败:', jsonError)
      return []
    }
  } catch (error) {
    console.error('获取数据日志失败:', error)
    return []
  }
}

// 开始滚动
const startScroll = () => {
  const container: any = document.querySelector('.scroll-container')
  const content: any = document.querySelector('.scroll-content')
  
  if (!container || !content) return
  
  // 克隆内容以实现无缝滚动
  const demo2: any = document.getElementById('demo2')
  if (demo2) {
    demo2.innerHTML = content.innerHTML
  }
  
  // 开始滚动定时器
  scrollTimer = setInterval(() => {
    if (container.scrollTop >= content.offsetHeight) {
      container.scrollTop = 0
    } else {
      container.scrollTop++
    }
  }, scrollSpeed)
}

// 停止滚动
const stopScroll = () => {
  if (scrollTimer) {
    clearInterval(scrollTimer)
    scrollTimer = null
  }
}

// 组件挂载时获取数据并开始滚动
onMounted(async () => {
  dataList.value = await getDataLogs()
  // 等待DOM更新后开始滚动
  setTimeout(() => {
    startScroll()
  }, 100)
})

// 组件销毁时停止滚动
onUnmounted(() => {
  stopScroll()
})
</script>

<style scoped>
.boxTitle2 {
  width: 100%;
  height: 10%;
  font-size: .6vw;
  text-align: center;
  line-height: 10%;
  margin-top: 1vw;
  color: #0efcff;
}

.scroll-container {
  height: 100%;
  overflow: hidden;
}

.scroll-container table {
  width: 100%;
  border-collapse: collapse;
}

.scroll-container td {
  padding: 8px 12px;
  white-space: nowrap;
}
</style>
